package com.pxxy.app_homepage.dao;

import com.pxxy.app_homepage.constant.InfoConstant;
import com.pxxy.app_homepage.entity.Information;
import com.pxxy.app_homepage.eventbus.GetTenInfoMessage;
import com.pxxy.app_homepage.utils.InfoJsonUtils;
import com.pxxy.lib_common.constant.ServerConstant;


import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class InfoDao {

    private static OkHttpClient okHttpClient = new OkHttpClient();

    public static void getTenInfo(int start) {
        //创建frombody对象
        FormBody formBody = new FormBody.Builder()
                .add(InfoConstant.INFO_GETTENINFO_START, String.valueOf(start))
                .build();
        //创建request对象
        Request request = new Request.Builder()
                .url(ServerConstant.INFO_GET_TEN_INFO_SERVER)
                .post(formBody)
                .build();
        //开始请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //创建eventbus消息对象
                GetTenInfoMessage message = new GetTenInfoMessage();
                //设置返回结果，失败
                message.setResult(GetTenInfoMessage.RESULT_FAILURE);
                //发布事件
                EventBus.getDefault().post(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //创建eventbus消息对象
                GetTenInfoMessage message = new GetTenInfoMessage();
                //获取返回数据
                String result = response.body().string();
                //判断结果
                if (result.equals(InfoConstant.SERVER_ERROR)) {
                    //设置返回结果，成功
                    message.setResult(GetTenInfoMessage.RESULT_SERVER_ERROR);
                } else {
                    //设置返回结果，成功
                    message.setResult(GetTenInfoMessage.RESULT_SERVER_ERROR);
                    List<Information> infos = InfoJsonUtils.jsonToInfoList(result);
                }

            }
        });
    }
}
